package cn.source.system.service.impl;

import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.List;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.source.common.config.AliyunConfig;
import cn.source.common.config.RuoYiConfig;
import cn.source.common.core.domain.AjaxResult;
import cn.source.common.utils.VideoUtils;
import cn.source.common.utils.uuid.IdUtils;
import cn.source.system.domain.AaCategory;
import cn.source.system.mapper.AaGoodsDaoMapper;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.source.system.mapper.AaGoodsMapper;
import cn.source.system.domain.AaGoods;
import cn.source.system.service.IAaGoodsService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 视频管理Service业务层处理
 * 
 * @author sourcebyte.vip
 * @date 2023-08-04
 */
@Service
public class AaGoodsServiceImpl implements IAaGoodsService 
{
    @Autowired
    private AaGoodsMapper aaGoodsMapper;
    @Autowired
    private RuoYiConfig ruoYiConfig;

    @Autowired
    private AaGoodsDaoMapper aaGoodsDaoMapper;
    @Autowired
    private AliyunConfig aliyunConfig;


    /**
     * 查询视频管理
     * 
     * @param id 视频管理主键
     * @return 视频管理
     */
    @Override
    public AaGoods selectAaGoodsById(Long id)
    {
        return aaGoodsMapper.selectAaGoodsById(id);
    }

    /**
     * 查询视频管理列表
     * 
     * @param aaGoods 视频管理
     * @return 视频管理
     */
    @Override
    public List<AaGoods> selectAaGoodsList(AaGoods aaGoods)
    {
        return aaGoodsMapper.selectAaGoodsList(aaGoods);
    }

    /**
     * 新增视频管理
     * 
     * @param aaGoods 视频管理
     * @return 结果
     */
    @Override
    public int insertAaGoods(AaGoods aaGoods) {
        aaGoods.setCreateDate(new Date());
        for (String s : aaGoods.getGoodsVideo().split(",")) {
            AaGoods newGoods = new AaGoods();
            BeanUtils.copyProperties(aaGoods, newGoods);
            newGoods.setGoodsVideo(s);
//            pathHandle(newGoods);
            aaGoodsMapper.insertAaGoods(newGoods);
        }
        return 1;
    }


    public void pathHandle(AaGoods aaGoods){
        if(StrUtil.isEmpty(aaGoods.getGoodsImage())||!aaGoods.getGoodsImage().contains(aaGoods.getGoodsVideo())){
            getLocalPath(aaGoods,0);
        }
        if(StrUtil.isEmpty(aaGoods.getGoodsVideo5())||!aaGoods.getGoodsVideo5().contains(aaGoods.getGoodsVideo())){
            getLocalPath(aaGoods,1);
        }
    }

    public void getLocalPath(AaGoods aaGoods,Integer type) {
        Integer index = StrUtil.ordinalIndexOf(aaGoods.getGoodsVideo(),"/",2);
        String pathhead = aaGoods.getGoodsVideo().substring(0,index);
        String pathtail = aaGoods.getGoodsVideo().substring(index);
        if(type.equals(0)){
            getImgPath(aaGoods,pathhead,pathtail);
        }else{
            getVdoPath(aaGoods,pathhead,pathtail);
        }
    }
    public void getImgPath(AaGoods aaGoods,String pathhead,String pathtail){
        String newId = IdUtils.fastUUID();
        String relativePath = StrUtil.format("{}{}.{}.jpg",pathhead,pathtail,newId);
        aaGoods.setGoodsImage(relativePath);
        String oldPath = StrUtil.format("{}{}",RuoYiConfig.getProfile(),pathtail);
        String newPath = StrUtil.format("{}{}.{}.jpg",RuoYiConfig.getProfile(),pathtail,newId);
        try{
            VideoUtils.getFrameFile(oldPath,newPath);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    public void getVdoPath(AaGoods aaGoods,String pathhead,String pathtail){
        String newId =  IdUtils.fastUUID();
        String relativePath = StrUtil.format("{}{}.{}{}",pathhead,pathtail,newId,pathtail.substring(pathtail.lastIndexOf(".")));
        aaGoods.setGoodsVideo5(relativePath);
        String oldPath = StrUtil.format("{}{}",RuoYiConfig.getProfile(),pathtail);
        String newPath = StrUtil.format("{}{}.{}{}",RuoYiConfig.getProfile(),pathtail,newId,pathtail.substring(pathtail.lastIndexOf(".")));
        VideoUtils.voidSplit(oldPath,newPath,RuoYiConfig.getFfmfile(),RuoYiConfig.getVideoStartTime(),RuoYiConfig.getVideoDuration());
    }

    /**
     * 修改视频管理
     * 
     * @param aaGoods 视频管理
     * @return 结果
     */
    @Override
    public int updateAaGoods(AaGoods aaGoods)
    {
//        pathHandle(aaGoods);
        return aaGoodsMapper.updateAaGoods(aaGoods);
    }

    public AjaxResult remogeFileOss(AaGoods aaGoods) throws Exception {
// Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = aliyunConfig.getEndpoint();//"https://oss-cn-beijing.aliyuncs.com";
        DefaultCredentialProvider credentialsProvider = CredentialsProviderFactory.newDefaultCredentialProvider(aliyunConfig.getAccessKeyId(), aliyunConfig.getSecretAccessKey());
        String bucketName = aliyunConfig.getBucketName();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            if(StrUtil.isNotEmpty(aaGoods.getGoodsImage())){
                ossClient.deleteObject(bucketName,aaGoods.getGoodsImage());
            }
            for (int i = 0; i < aaGoods.getGoodsVideo().split(",").length; i++) {
                String path = aaGoods.getGoodsVideo().split(",")[i];
                if(StrUtil.isNotEmpty(path)){
                    ossClient.deleteObject(bucketName,path);
                }
            }

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        AjaxResult ajax = AjaxResult.success();
        return ajax;
    }

    /**
     * 批量删除视频管理
     * 
     * @param ids 需要删除的视频管理主键
     * @return 结果
     */
    @Override
    public int deleteAaGoodsByIds(Long[] ids)
    {
        int count = 0;
        for (int i = 0; i < ids.length; i++) {
            AaGoods goods = selectAaGoodsById(ids[i]);
            removeResource(goods);
            if (ObjectUtil.isNotEmpty(goods)) {
                goods.setDelStatus(1);
                count += aaGoodsMapper.updateAaGoods(goods);
            }
        }
        return count;
//        return aaGoodsMapper.deleteAaGoodsByIds(ids);
    }

    public void removeResource(AaGoods aaGoods){
        try{
            remogeFileOss(aaGoods);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    /**
     * 删除视频管理信息
     * 
     * @param id 视频管理主键
     * @return 结果
     */
    @Override
    public int deleteAaGoodsById(Long id)
    {

        return aaGoodsMapper.deleteAaGoodsById(id);
    }

    @Override
    public List<AaGoods> queryListByCategoryId(Long cid , Long userId) {
        return aaGoodsDaoMapper.queryListByCategoryId(cid , userId);
    }
}
